import * as vscode from 'vscode';
import { I18nService } from '../services/i18nService';

export class I18nReferenceProvider implements vscode.ReferenceProvider {
    constructor(private i18nService: I18nService) {}

    public async provideReferences(
        document: vscode.TextDocument,
        position: vscode.Position,
        _context: vscode.ReferenceContext,
        _token: vscode.CancellationToken
    ): Promise<vscode.Location[]> {
        // Check if we're in a JSON file in the i18n directory
        if (!document.fileName.includes('i18n') || !document.fileName.endsWith('.json')) {
            return [];
        }

        // Get the translation key at the current position
        const line = document.lineAt(position.line).text;
        const keyMatch = /"([^"]+)":\s*"[^"]*"/.exec(line);
        if (!keyMatch) {
            return [];
        }

        // Get the full key path by traversing up the JSON structure
        const fullKey = await this.getFullKeyPath(document, position.line, keyMatch[1]);
        if (!fullKey) {
            return [];
        }

        // Find all references in Python files
        const references = await this.findReferences(fullKey);
        return references;
    }

    private async getFullKeyPath(document: vscode.TextDocument, currentLine: number, lastKey: string): Promise<string | null> {
        const keys: string[] = [lastKey];
        let curlyBraceCount = 0;
        
        // Scan upwards to build the full key path
        for (let line = currentLine; line >= 0; line--) {
            const text = document.lineAt(line).text;
            
            // Count curly braces to track JSON structure
            curlyBraceCount += (text.match(/{/g) || []).length;
            curlyBraceCount -= (text.match(/}/g) || []).length;
            
            const keyMatch = /"([^"]+)":\s*{/.exec(text);
            if (keyMatch && curlyBraceCount > 0) {
                keys.unshift(keyMatch[1]);
            }
        }

        return keys.join('.');
    }

    private async findReferences(translationKey: string): Promise<vscode.Location[]> {
        const locations: vscode.Location[] = [];
        const files = await vscode.workspace.findFiles(
            '**/*.py',
            '**/node_modules/**'
        );

        const pattern = new RegExp(`t\\(['"](${translationKey})['"](\\)|,)`, 'g');

        for (const file of files) {
            const document = await vscode.workspace.openTextDocument(file);
            const text = document.getText();
            const matches = Array.from(text.matchAll(pattern));

            for (const match of matches) {
                const pos = document.positionAt(match.index! + 3); // Skip t("
                const range = new vscode.Range(
                    pos,
                    pos.translate(0, translationKey.length)
                );
                locations.push(new vscode.Location(file, range));
            }
        }

        return locations;
    }
} 